<template>
	<Split v-model="split" class="container">
		<div slot="left" class="left">
			<Tree :data="orgTree" @on-select-change="treeSelected"></Tree>
		</div>
		<div slot="right" class="right">
			<Layout style="padding:0 24px 24px;height:100%;">
				<Breadcrumb style="margin:24px 0">
					<BreadcrumbItem>首页</BreadcrumbItem>
					<BreadcrumbItem>用户管理</BreadcrumbItem>
					<BreadcrumbItem v-if="currentNode.title">{{currentNode.title}}</BreadcrumbItem>
				</Breadcrumb>
				<Form inline>
					<ButtonGroup style="margin-right:24px;">
						<Button title="新增" :disabled="!currentNode.data" icon="md-add" @click="editModal=true"></Button>
						<Button title="移除到独立用户" :disabled="!currentNode.data" icon="md-cut" @click="moveToTrash"></Button>
						<Button title="彻底删除" :disabled="!currentNode.data" icon="md-trash" @click="removeBatch"></Button>
						<Button title="更换组织" :disabled="selection.length <= 0" icon="ios-flag" @click="changeOrgModal=true"></Button>
						<Button title="更换角色" :disabled="selection.length <= 0" icon="ios-key" @click="changeRoleModal=true"></Button>
					</ButtonGroup>
					<FormItem>
						<Input type="text" placeholder="登录名" clearable v-model="pageRequest.condition.loginName" />
					</FormItem>
					<FormItem>
						<Input type="text" placeholder="姓名" clearable v-model="pageRequest.condition.realName" />
					</FormItem>
					<FormItem>
						<Input type="text" placeholder="手机号" clearable v-model="pageRequest.condition.mobile" />
					</FormItem>
					<FormItem>
						<Button type="primary" icon="ios-search" shape="circle" @click="list">组织内查询</Button>
						<Button type="warning" icon="ios-search" shape="circle" @click="listAll" style="margin-left:10px;">全部查询</Button>
					</FormItem>
				</Form>
				<Content ref="content" style="padding:0;background:#fff;">
					<Table :loading="loading" :columns="tableColumns" :data="pageData.content" :height="tableHeight"
					 @on-selection-change="onSelectionChange" border>
						<template slot-scope="{ row, index }" slot="action">
							<Button type="warning" size="small" style="margin-right: 5px" @click="modify(row)">修改</Button>
							<Button type="error" size="small" style="margin-right: 5px" @click="remove(row)">删除</Button>
							<Button type="primary" size="small" @click="openRoleModal(row)">角色分配</Button>
						</template>
						<template slot="footer">
							<Page style="margin-left:10px;" :total="pageData.total" :current="pageData.page" :page-size="15" @on-change="changePage"></Page>
						</template>
					</Table>
				</Content>
				<!-- 用户编辑对话框 -->
				<Modal :width="800" v-model="editModal" @on-visible-change="onVisibleChange" title="编辑用户信息" footer-hide>
					<Form ref="userForm" :model="userInfo" :label-width="80" :rules="userRules">
						<Row :gutter="5">
							<Col span="12">
							<FormItem label="登录名" prop="loginName">
								<Input v-model="userInfo.loginName" type="text" placeholder="请输入登录名" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="密码" prop="password">
								<Input v-model="userInfo.password" type="password" placeholder="请输入密码" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="姓名" prop="realName">
								<Input v-model="userInfo.realName" type="text" placeholder="请输入性名" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="性别" prop="sexCode">
								<RadioGroup v-model="userInfo.sexCode">
									<Radio label="UNKNOWN" checked>未知</Radio>
									<Radio label="MALE">男</Radio>
									<Radio label="FEMALE">女</Radio>
								</RadioGroup>
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="手机号" prop="mobile">
								<Input v-model="userInfo.mobile" type="text" placeholder="请输入手机号" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="昵称" prop="nickName">
								<Input v-model="userInfo.nickName" type="text" placeholder="请输入昵称" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="编号" prop="userCode">
								<Input v-model="userInfo.userCode" type="text" placeholder="请输入编号" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="职位" prop="position">
								<Input v-model="userInfo.position" type="text" placeholder="请输入职位" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="证件号码" prop="cardId">
								<Input v-model="userInfo.cardId" type="text" placeholder="请输入证件号码" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="居住地址" prop="address">
								<Input v-model="userInfo.address" type="text" placeholder="请输入居住地址" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="邮箱" prop="email">
								<Input v-model="userInfo.email" type="text" placeholder="请输入邮箱" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="IP" prop="limitIp">
								<Input v-model="userInfo.limitIp" type="text" placeholder="请输入登录限制IP" />
							</FormItem>
							</Col>
							<Col span="12">
							<FormItem label="序号" prop="sequence">
								<Input v-model="userInfo.sequence" type="number" placeholder="请输入序号" />
							</FormItem>
							</Col>
						</Row>
						<Row :gutter="16">
							<Col>
							<FormItem>
								<Button type="primary" @click="save">保存</Button>
							</FormItem>
							</Col>
						</Row>
					</Form>
				</Modal>
				<!-- 更换组织对话框 -->
				<Modal :width="800" v-model="changeOrgModal" title="请选择需要更换的组织" footer-hide>
					<div class="org-tree-modal">
						<Tree ref="orgModal" :data="changeOrgTree"></Tree>
					</div>
					<Button @click="changeUserOrg" type="primary" style="margin-top: 10px;">确定</Button>
				</Modal>
				<!-- 修改角色对话框 -->
				<Modal :width="400" v-model="changeRoleModal" @on-visible-change="onRoleModalVisibleChange" title="角色分配" footer-hide>
					<div class="auth-list-content">
						<Select v-model="roleSelection" multiple>
							<Option v-for="item in roleList" :value="item.id" :key="item.id">
								{{item.roleName}}
							</Option>
						</Select>
					</div>
					<Button type="primary" @click="saveUserRole">确定</Button>
					<Button type="warning" @click="changeRoleModal=false" style="margin-left:5px;">取消</Button>
				</Modal>
			</Layout>
		</div>
	</Split>
</template>

<script language="JavaScript">
	export default {
		components: {},
		data() {
			return {
				split: 0.15,
				tableHeight: 100, // 自适应表格高度
				loading: false, // 加载中
				orgTree: [], // 组织树
				changeOrgTree: [], // 改变组织的树
				currentNode: {}, // 当前选中的节点
				tableColumns: [{
					type: 'selection',
					width: 80
				}, {
					title: '登录名',
					key: 'loginName',
					width: 150,
					resizable: true
				}, {
					title: '姓名',
					key: 'realName',
					width: 150,
					resizable: true
				}, {
					title: '昵称',
					key: 'nickName',
					width: 150,
					resizable: true
				}, {
					title: '性别',
					key: 'sexName',
					width: 150,
					resizable: true
				}, {
					title: '手机号',
					key: 'mobile',
					width: 150,
					resizable: true
				}, {
					title: '证件号码',
					key: 'cardId',
					width: 250,
					resizable: true
				}, {
					title: '序号',
					key: 'sequence',
					width: 100,
					resizable: true
				}, {
					title: '操作',
					slot: 'action',
					width: 250
				}], // 数据表格定义
				// 分页请求
				pageRequest: {
					page: 1,
					rows: 15,
					sort: "sequence:asc",
					condition: {}
				},
				// 分页查询结果
				pageData: {
					page: 1,
					total: 2,
					content: [], // 表格数据
				},
				editModal: false, // 用户编辑对话框
				userInfo: {
					loginName: '', // 登录名
					sexCode: 'UNKNOWN', //默认性别未知
					sequence: 0, // 序号
				}, // 要保存的用户信息
				userRules: {
					loginName: [{
						required: true,
						message: '必填'
					}],
					sequence: [{
						required: true,
						message: '必填'
					}]
				}, // 用户编辑表单校验
				selection: [], // 已选择的表格数据
				changeOrgModal: false, // 修改组织对话框
				changeRoleModal: false, // 修改角色对话框
				currentUserInfo: {}, // 当前操作的用户信息
				roleList: [], // 角色列表
				roleSelection: [], // 选中的角色列表
			}
		},
		computed: {},
		watch: {},
		created: function() {},
		mounted: function() {
			this.$nextTick(() => {
				this.tableHeight = this.$refs.content.$el.clientHeight
				this.getOrgTree()
				this.getRoleList()
			})
		},
		methods: {
			// 获取组织树
			getOrgTree: function() {
				this.$request.get('/admin/sys/org/tree', {}, res => {
					this.orgTree = res.data || []
					// 复制一份
					let tj = JSON.stringify(this.orgTree)
					this.changeOrgTree = JSON.parse(tj)
					// 增加一个固定的独立用户组
					this.orgTree.push({
						title: "独立用户",
						data: {
							id: -1,
							orgCode: 'NON_GROUP',
							orgName: '独立用户',
							aliasName: '独立用户'
						}
					})
				})
			},
			// 选中组织节点
			treeSelected: function(list, item) {
				this.currentNode = item
				this.userInfo.orgId = item.data.id
				this.pageRequest.condition.orgId = item.data.id
				this.list()
			},
			// 分页
			changePage: function(page) {
				this.pageRequest.page = page
				this.list()
			},
			// 用户列表
			list: function() {
				this.$request.post('/admin/sys/user/list', this.pageRequest, res => {
					this.pageData = res.data || this.pageData
				}, false, false)
			},
			// 用户列表
			listAll: function() {
				let prJson = JSON.stringify(this.pageRequest);
				let pr = JSON.parse(prJson)
				pr.condition.orgId = ''
				this.$request.post('/admin/sys/user/list', pr, res => {
					this.pageData = res.data || this.pageData
				}, false, false)
			},
			// 关闭对话框
			onVisibleChange: function() {
				this.$refs['userForm'].resetFields()
				this.userInfo.id = ''
			},
			// 保存用户
			save: function() {
				if (!this.userInfo.orgId) {
					this.$Message.warning('请选择所在组织')
					return
				}
				this.$refs['userForm'].validate(valid => {
					if (valid) {
						this.$request.post('/admin/sys/user/save', this.userInfo, res => {
							this.editModal = false
							this.list()
						}, true, true)
					}
				})
			},
			// 修改用户
			modify: function(row) {
				this.editModal = true
				this.$nextTick(() => {
					this.userInfo = Object.assign({}, row)
					this.userInfo.password = ''
				})
			},
			// 删除用户
			remove: function(row) {
				this.$Modal.confirm({
					title: '确认？',
					content: '删除后不可恢复，是否继续？',
					onOk: () => {
						this.$request.post('/admin/sys/user/delete', row, res => {
							this.list()
						}, true, true)
					}
				})
			},
			// 表格多选事件
			onSelectionChange: function(sel) {
				this.selection = sel
			},
			// 批量删除
			removeBatch: function() {
				let ids = this.$utils.getPropertyArrayFromObjectArray(this.selection, 'id')
				if (ids && ids.length > 0) {
					this.$Modal.confirm({
						title: '确认？',
						content: '删除后不可恢复，确删除？',
						onOk: () => {
							this.$request.post('/admin/sys/user/deleteBatch', ids, res => {
								this.list()
							}, true, true)
						}
					})
				} else {
					this.$Message.warning('请选择人员')
				}
			},
			// 更换到独立用户
			moveToTrash: function() {
				let ids = this.$utils.getPropertyArrayFromObjectArray(this.selection, 'id')
				if (ids && ids.length > 0) {
					this.$Modal.confirm({
						title: '确认？',
						content: '确认将相关人员移出到独立用户？',
						onOk: () => {
							this.$request.post('/admin/sys/user/changeUserOrg', {
								orgId: -1,
								userIds: ids
							}, res => {
								this.list()
							}, true, true)
						}
					})
				} else {
					this.$Message.warning('请选择人员')
				}
			},
			// 更换组织
			changeUserOrg: function() {
				let ids = this.$utils.getPropertyArrayFromObjectArray(this.selection, 'id')
				if (!ids || ids.length == 0) {
					this.$Message.warning('请选择用户')
					return
				}
				let nodes = this.$refs['orgModal'].getSelectedNodes()
				if (nodes && nodes.length > 0) {
					let orgId = nodes[0].data.id
					this.$Modal.confirm({
						title: '确认？',
						content: '确认更换这些人员所在的组织？',
						onOk: () => {
							this.$request.post('/admin/sys/user/changeUserOrg', {
								orgId: orgId,
								userIds: ids
							}, res => {
								this.changeOrgModal = false
								this.list()
							}, true, true)
						}
					})
				} else {
					this.$Message.warning('请选择组织')
				}
			},
			// 获取角色列表
			getRoleList: function() {
				this.$request.post('/admin/sys/role/list', {
					page: 1,
					rows: 99999,
					sort: 'sequence:asc'
				}, res => {
					this.roleList = (res.data || {}).content || []
				}, false, false)
			},
			// 角色对话框改变事件
			onRoleModalVisibleChange: function(open) {
				if (!open) {
					this.roleSelection = []
				}
			},
			// 打开角色分配对话框
			openRoleModal: function(row) {
				this.$request.get(`/admin/sys/user-role/getIds/${row.id}`, {}, res => {
					this.roleSelection = res.data || []
				}, false, false)
				this.changeRoleModal = true
				this.currentUserInfo = row
				this.selection = []
			},
			// 更换角色
			saveUserRole: function() {
				let userIds = this.$utils.getPropertyArrayFromObjectArray(this.selection, 'id')
				if (!userIds || userIds.length == 0) {
					userIds = [this.currentUserInfo.id]
				}
				let userRoleInfo = {
					userIds: userIds,
					roleIds: this.roleSelection
				}
				console.log(userRoleInfo)
				this.$Modal.confirm({
					title: '确认？',
					content: '确认修改用户角色？',
					onOk: () => {
						this.$request.post('/admin/sys/user-role/save', userRoleInfo, res => {
							this.changeRoleModal = false
						}, true, true)
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped="scoped">
	.container {
		height: 100%;
		background-color: white;

		.left {
			overflow-y: auto;
			overflow-x: hidden;
			height: 100%;
			padding: 10px 20px;
			background-color: white;
		}

		.right {
			height: 100%;
		}
	}

	.org-tree-modal {
		width: 100%;
		height: 450px;
		overflow-y: auto;
	}
	
	.auth-list-content {
		height: 450px;
		overflow-y: auto;
	}
</style>
